﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.Admin; 
using Services.WXProjectAdmin;
using Xproject.Util;
using System.Text;

namespace WeiXinpProAdmin.Controllers
{
    public class SystemController : AdminBaseController
    {
        SystemMenuServices m_SystemMenuServices;
        SystemRoleServices m_SystemRoleServices;
        AdminUserInfoServices m_AdminUserInfoServices;
        public SystemController(SystemMenuServices mSystemMenuServices, SystemRoleServices mSystemRoleServices, AdminUserInfoServices mAdminUserInfoServices)
        {
            m_SystemMenuServices = mSystemMenuServices;
            m_SystemRoleServices = mSystemRoleServices;
            m_AdminUserInfoServices = mAdminUserInfoServices;
        }

        #region ActionResult
       
            #region 菜单相关视图
        public ActionResult MenuEdit(int? menuId, int? level)
        {
            AdminMenu model =null;
            List<AdminMenu> parentList = new List<AdminMenu>();
            string title ="新增顶级菜单";
            if (!menuId.HasValue)
            {
                if (level.HasValue && level.Value > 1) //有值 并且不是顶级此菜单
                {
                    //得到此level的父级们 (level -1)
                    parentList = m_SystemMenuServices.GetLevelMenuList(Site, level.Value - 1);
                    title = "新增"+(level.Value==2?"二级菜单":"三级菜单");
                }
            }
            else { //编辑状态
                if (level.HasValue && level.Value > 1) //有值 并且不是顶级此菜单
                {
                    //得到此level的父级们 (level -1)
                    parentList = m_SystemMenuServices.GetLevelMenuList(Site, level.Value - 1);                  
                }
                model =  m_SystemMenuServices.GetAdminMenuByMenuId(menuId.Value);
                title = "编辑菜单";
            }
            ViewBag.Title = title;
            ViewBag.Level = level;
            ViewData["parentList"] = parentList;
            return View(model);
        }
        public ActionResult MenuList()
        {
            return View();
        }
        #endregion

            #region 角色相关视图
        public ActionResult RoleList()
        {
            return View();
        }
        public ActionResult RoleEdit(int? roleId)
        {
            AdminRole model = null;
         
            string title = "新增角色";
            if (roleId.HasValue)
            {
                //编辑状态               
                model = m_SystemRoleServices.GetAdminRoleByRoleId(roleId.Value);
                title = "编辑角色";
            }
            
            ViewBag.Title = title;
         
            return View(model);
        }
        #endregion

            #region 后台用户相关视图
        public ActionResult AdminUserEdit(string Id)
        {
            AdminUser model = null;

            string title = "新增用户";
            if (!string.IsNullOrEmpty(Id))
            {
                //编辑状态               
                model = m_AdminUserInfoServices.GetById(Id);
                title = "编辑用户";
            }

            ViewBag.Title = title;

            return View(model);           
        }
        public ActionResult AdminUserList() {
            return View();
        }
        #endregion

            #region 用户角色相关视图
        public ActionResult AdminUserRoleEdit(int userID)
        {
            //先得到所有角色
            int total = 0;
            List<AdminRole> roles =  m_SystemRoleServices.GetAdminRoleList(Site);
            List<AdminUserRole> userRoles = m_AdminUserInfoServices.GetUserRoles(userID);
            List<int> rolesId = userRoles.Select(i => i.RoleID).ToArray().ToList<int>();
            ViewData["historyroles"] = rolesId;
            ViewBag.userId = userID;
            return View(roles);
        }
        #endregion

        #region 角色菜单相关视图
        public ActionResult RoleMenuEdit(int roleId)
        {
            //先得到此角色拥有的菜单信息
            List<AdminRoleMenu> roleMenus = m_SystemMenuServices.GetRoleMenus(roleId);
            List<int> roleMenuIds = roleMenus.Select(i => i.MenuId).ToList();
            List<AdminMenu> menus = m_SystemMenuServices.GetAdminMenuList(Site);
            //构造ztree数据
            StringBuilder sb = new StringBuilder();
            if (menus != null && menus.Count > 0)
            {
                //全局只设定三级菜单 level 1 - 3
                sb.Append("{ id: 0, pId: null, name: '系统菜单',open:true },");
                string strchecked = "";
                foreach (AdminMenu arm in menus)
                {
                    if (roleMenuIds.Contains(arm.MenuId))
                    {
                        strchecked = ", checked:true";
                    }
                    string temp = "{ id: "+arm.MenuId+", pId: "+arm.MenuParentId+", name: '"+arm.MenuName+ "',open:true "+ strchecked + " },";
                    sb.Append(temp);
                }              
            }
            string ztreeJson = sb.ToString().TrimEnd(',');
            ViewBag.ztreeJson = ztreeJson;
            ViewBag.roleId = roleId;
            return View();
        }
            #endregion

        #endregion

        #region JsonResult  

            #region 菜单相关操作
        public JsonResult DelAdminMenu(int menuId) {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (menuId > 0)
            {
                AdminMenu menu = m_SystemMenuServices.GetAdminMenuByMenuId(menuId);
                success = m_SystemMenuServices.DelMenu(menu);
                result = success ? "删除成功" : "删除失败";
                if (success) {
                    Cache_SystemInfo.ClearMenus();
                }
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EditMenu(FormCollection collection)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string  MenuId = collection["menuId"];
            AdminMenu menu = new AdminMenu();
            if (!string.IsNullOrEmpty(MenuId))
            {
                int menuid = 0;
                int.TryParse(MenuId, out menuid);
                menu = m_SystemMenuServices.GetAdminMenuByMenuId(menuid);
            }                
            menu.MenuUrl = collection["MenuUrl"];
            menu.MenuName = collection["MenuName"];
            menu.MenuDesc = collection["MenuDesc"];
            menu.MenuParentId = int.Parse(collection["MenuParentId"] ?? "0");
            menu.MenuOrder = int.Parse(collection["MenuOrder"] ?? "0");
            menu.MenuIcon = collection["MenuIcon"];
            string enable = collection["Enable"];
            menu.Enable = int.Parse(string.IsNullOrEmpty(enable) ? "0" : ((enable.ToString() == "on") ? "1" : "0"));
            if (menu.MenuParentId != 0 && Cache_SystemInfo.AdminMenus!=null)
            {
                AdminMenu temp =Cache_SystemInfo.AdminMenus.Where(i => i.MenuId == menu.MenuParentId).FirstOrDefault();
                if (temp != null)
                {
                    menu.MenuParentName = temp.MenuName;
                }
            }
            menu.MenuLevel = int.Parse(collection["MenuLevel"] ?? "0");
            if (!string.IsNullOrEmpty(MenuId)) // 如果MenuId 不为空，说明是编辑
            {                
                success= m_SystemMenuServices.EditMenu(menu, CurrentUser.UserID.ToString());
                Cache_SystemInfo.ClearMenus();
                result = (success) ? "编辑菜单成功！" : "编辑菜单失败！";
            }
            else //新增菜单
            {
                menu.Site = Site;
                success = m_SystemMenuServices.AddMenu(menu,CurrentUser.UserID.ToString());
                Cache_SystemInfo.ClearMenus();
                result = (success) ? "添加菜单成功！" : "添加菜单失败！";                                        
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetMenuList(int limit, int offset, string menuName, string menuDesc,string order,string ordername)
        {
            var lstRes = new List<AdminMenu>();
            int total = 0;
            lstRes= m_SystemMenuServices.GetAdminMenuList(Site, offset, limit,menuName,menuDesc,out total);                       
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }

            #endregion

            #region 角色相关操作
        public JsonResult DelAdminRole(int roleId) {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (roleId > 0)
            {
                AdminRole role = m_SystemRoleServices.GetAdminRoleByRoleId(roleId);
                success = m_SystemRoleServices.DelRole(role);
                result = success ? "删除成功" : "删除失败";
                if (success)
                {
                    Cache_SystemInfo.ClearRoles();
                }
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        public JsonResult EditAdminRole(FormCollection collection) {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string RoleId = collection["roleId"];
            AdminRole role = new AdminRole();
            if (!string.IsNullOrEmpty(RoleId))
            {
                int roleId = 0;
                int.TryParse(RoleId, out roleId);
                role = m_SystemRoleServices.GetAdminRoleByRoleId(roleId);
            }
            
            role.RoleName = collection["RoleName"];
            role.RoleDesc = collection["RoleDesc"];                      
            role.RoleIcon = collection["RoleIcon"];
            string enable = collection["Enable"];
            role.Enable = int.Parse(string.IsNullOrEmpty(enable) ? "0" : ((enable.ToString() == "on") ? "1" : "0"));                      
            if (!string.IsNullOrEmpty(RoleId)) // 如果RoleId 不为空，说明是编辑
            {
                success = m_SystemRoleServices.EditRole(role, CurrentUser.UserID.ToString());
                Cache_SystemInfo.ClearRoles();
                result = (success) ? "编辑角色成功！" : "编辑角色失败！";
            }
            else //新增角色
            {
             
                success = m_SystemRoleServices.AddRole(role, CurrentUser.UserID.ToString());
                Cache_SystemInfo.ClearRoles();
                result = (success) ? "添加角色成功！" : "添加角色失败！";
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetRoleList(int limit, int offset, string roleName, string roleDesc, string order, string ordername) {
            var jsonData = new Object();                
            var lstRes = new List<AdminRole>();
            int total = 0;
             lstRes = m_SystemRoleServices.GetAdminRoleList(Site, offset, limit, roleName, roleDesc, out total);
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);            
        }
        #endregion

            #region 系统用户相关操作
        public JsonResult GetAdminUserList(int limit, int offset, string userName, int? userCode,string mobile,string email,
            DateTime? startTime,DateTime? endTime, string order, string ordername)
        {
            var jsonData = new Object();
            var lstRes = new List<AdminUser>();
            int total = 0;
            lstRes = m_AdminUserInfoServices.GetAllAdminUser(Site, offset, limit, userName, userCode, mobile, email, startTime, endTime, order, ordername, out total);           
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DelAdminUser(string Id)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (!string.IsNullOrEmpty(Id))
            {
                AdminUser user = m_AdminUserInfoServices.GetById(Id);
                success = m_AdminUserInfoServices.DelAdminUser(user);
                result = success ? "删除成功" : "删除失败";                
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EditAdminUser(FormCollection collection)
        {
           
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string password = collection["Password"];
            string comfirmPassword = collection["ComfirmPassword"];
            if (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(comfirmPassword))
            {
                if (password != comfirmPassword) {
                    jsonData = new { Success = false, Data = "两次密码不一致！" };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
            }
            string Id = collection["ID"];
            AdminUser user = new AdminUser();
            if (!string.IsNullOrEmpty(Id))
            {
                user = m_AdminUserInfoServices.GetById(Id);
            }

            user.UserName = collection["UserName"];
            user.Email = collection["Email"];
            user.Mobile = collection["Mobile"];
            string enable = collection["Enable"];
            user.Password = CommonHelper.MD5(password);

            user.Enable = int.Parse(string.IsNullOrEmpty(enable) ? "0" : ((enable.ToString() == "on") ? "1" : "0"));
            if (!string.IsNullOrEmpty(Id)) // 如果 Id 不为空，说明是编辑
            {
                success = m_AdminUserInfoServices.EditAdminUser(user, CurrentUser.UserID.ToString());                
                result = (success) ? "编辑用户成功！" : "编辑用户失败！";
            }
            else //新增用户
            {
               
                success = m_AdminUserInfoServices.AddAdminUser(user, CurrentUser.UserID.ToString());                
                result = (success) ? "添加用户成功！" : "添加用户失败！";
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        #endregion

            #region 用户角色配置相关操作

        public JsonResult EditUserRoles(int userId, int[] roleIds)
        {

            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;

            List<AdminUserRole> newroles = new List<AdminUserRole>();
            foreach (var i in roleIds)
            {
                AdminUserRole temp = new AdminUserRole();
                temp.ID = Guid.NewGuid().ToString();
                temp.UserID = userId;
                temp.RoleID = (int)i;
                newroles.Add(temp);
            }

            success =  m_SystemRoleServices.UpdateUserRoles(userId,newroles);         
            result = success ? "编辑成功" : "编辑失败";            
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region 角色分配菜单相关操作

        public JsonResult EditRoleMenus(int roleId, int[] menuIds)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            List<AdminRoleMenu> newroleMenus= new List<AdminRoleMenu>();
            foreach (var i in menuIds)
            {
                AdminRoleMenu temp = new AdminRoleMenu();
                temp.ID = Guid.NewGuid().ToString();
                temp.RoleId = roleId;
                temp.MenuId = (int)i;
                newroleMenus.Add(temp);
            }
            success = m_SystemMenuServices.UpdateRoleMenus(roleId, newroleMenus);
            result = success ? "编辑成功" : "编辑失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
            #endregion
        #endregion
    }
}